import Taro from "@tarojs/taro";

export const wrap = <T>(url, options): Promise<T> => {
  return new Promise(async (resolve, reject) => {
    const token = Taro.getStorageSync("token");

    Taro.request({
      url: process.env.API_URL + url,
      header: {
        Authorization: "Bearer " + token,
      },
      ...options,
      success: (res) => {
        if (res.data.code === 400) {
          const error =
            res.data.msg?.[0] || res.data.message?.[0] || "未知错误";
          Taro.showToast({
            title: error,
            icon: "none",
          });
          reject(new Error(error));
        } else if (res.data.code === 401) {
          Taro.clearStorageSync("token");
          Taro.redirectTo({
            url: "/pages/login/login",
          });
          reject(new Error("token无效"));
        } else {
          const data = res.data;
          resolve(data.data);
        }
      },
      fail: (err) => reject(err),
    });
  });
};

export const uploadImage = (path: string): Promise<string> => {
  return new Promise(async (resolve, reject) => {
    const token = Taro.getStorageSync("token");

    Taro.uploadFile({
      url: process.env.UPLOAD_URL,
      header: {
        Authorization: "Bearer " + token,
      },
      filePath: path,
      name: "file",
      success: (res) => {
        const data = res.data;
        resolve(JSON.parse(data));
      },
      fail: (err) => {
        reject(err);
      },
    });
  });
};

export default uploadImage;
